package com.sc.app.security.openidauth;

import com.sc.security.properties.SecurityConstants;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author sc
 * Created on  2018/1/24
 */
public class OpenIdAuthFilter extends AbstractAuthenticationProcessingFilter {

    private String openIdParameter = SecurityConstants.DEFAULT_PARAMETER_NAME_OPENID;
    private String providerIdParameter = SecurityConstants.DEFAULT_PARAMETER_NAME_PROVIDERID;
    private boolean postOnly = true;

    protected OpenIdAuthFilter( ) {
        super(new AntPathRequestMatcher(SecurityConstants.DEFAULT_LOGIN_PAGE_URL_OPENID,"POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        if(postOnly&&!request.getMethod().equals("POST")){
            throw new AuthenticationServiceException("方法不支持");
        }
        String openID = obtainOpenId(request);
        String providerId = obtainProviderId(request);
        if(openID==null){
            openID="";
        }
        if(providerId==null){
            providerId="";
        }
        openID=openID.trim();
        providerId=providerId.trim();

        OpenIdAuthToken openIdAuthToken = new OpenIdAuthToken(openID,providerId);
        setDetails(request,openIdAuthToken);
        return this.getAuthenticationManager().authenticate(openIdAuthToken);
    }

    private void setDetails(HttpServletRequest request, OpenIdAuthToken openIdAuthToken) {
        openIdAuthToken.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }

    private String obtainProviderId(HttpServletRequest request) {
        return request.getParameter(providerIdParameter);
    }

    private String obtainOpenId(HttpServletRequest request) {
        return request.getParameter(openIdParameter);
    }
}
